<template>

  <div>

    <Card>

      <div class="p-relative" style="padding-top: 10px;">
        <div @click="refresh" class="p-absolute refresh-btn">
          <Icon size='24' type="md-refresh" />
        </div>
        <div class="flex-box search-area">
          <div class="flex-item search-btn">
            <Button type="warning" @click='create'>添加</Button>
          </div>

        </div>
      </div>
      <Table :columns="tableOption" :data="data.list" border :no-data-text="loadingText ? loadingText : '暂无数据'" border
        ref="tables" editable search-place="top">


        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">
            <Button type='warning' @click="edit(row, index)" size='small'>编辑</Button>
            <Button type='error' @click="del(row, index)" size='small'>删除</Button>
          </div>
        </template>
      </Table>
      <Page class="foot-page" :current='page.current' :total="page.total" :page-size="page.pageSize" show-total
        show-elevator @on-change="changepage"></Page>

    </Card>


    <!-- 添加弹窗 -->
    <Modal v-model="createModal" :title="createTitle" width='700'>
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
        <FormItem label="标题名称" prop="name">
          <Input v-model="formValidate.name" placeholder="请输入标题名称"></Input>
        </FormItem>
        <FormItem label="位置" prop="location">
          <Select v-model="formValidate.location" style="width:130px" placeholder='请选择位置'>
            <Option v-for="(item,index) in data.locationList" :value="index" :key="index">{{item}} </Option>
          </Select>
        </FormItem>
        <FormItem label="状态">
          <RadioGroup v-model="formValidate.status">
            <Radio label="1">开启</Radio>&nbsp;&nbsp;&nbsp;&nbsp;
            <Radio label="0">关闭</Radio>&nbsp;&nbsp;&nbsp;&nbsp;
          </RadioGroup>
        </FormItem>
        <FormItem label=" ">
          <Button type="primary" @click="upload('album')">
            <Icon type="md-add" />
            上传图片(尺寸：828*552)
          </Button>
          <!-- 图片表格 -->
          <div class="detail-table border" v-if="prodGroupBasicObj.album_imageArr.length>0">
            <div class="base-info" style="margin: 0;margin-top: 15px;">
              <Row class='row-main-title text-center   table-head-bg  '>
                <Col span="11">图片</Col>
                <Col span="4">排序</Col>
                <Col span="6">状态</Col>
                <Col span="3">操作</Col>
              </Row>
              <Row class='row-main-title text-center' v-for="(item,index) in prodGroupBasicObj.album_imageArr">
                <Col class="padding10" span="11">
                <img :src="item.url.url?item.url.url:item.url"
                  style="width: 40px;height: 40px;border: 1px solid #eeeeee;" />
                </Col>
                <Col class="padding10" span="4"><Input type="text" style="text-align: center;" v-model="item.sort" />
                </Col>
                <Col class="padding10" span="6">
                <i-switch true-color="#FF9F60" v-model="item.status" size="large">
                  <span slot="open">启用</span>
                  <span slot="close">禁用</span>
                </i-switch>
                </Col>
                <Col class="padding10" span="3">
                <Button type='error' @click="delImg(item,index)" size='small' v-if="item.url.url">删除</Button>
                </Col>
              </Row>

            </div>
          </div>
        </FormItem>

      </Form>
      <div slot="footer">
        <Button type="warning" @click="save('formValidate')" :disabled="isDisable" :loading="isLoading">保存</Button>
      </div>
    </Modal>


    <Modal v-model="uploadModal" title="图片管理" class="uploadModal-wrap" :closable='isClosable'>
      <!-- 上传组件 -->
      <div>
        <UploadTool :showUpload='showUpload' :optionObj='uploadImgPathList' @getSelectedImgList='getSelectedImgList'>
        </UploadTool>
      </div>
      <div slot="footer">
        <Button @click='cancelUploadModal'>取消</Button>
        <Button type="primary" @click='confirm(uploadType)'>确定</Button>
      </div>
    </Modal>

    <!-- 删除弹窗 -->
    <Modal v-model="delModal" title="提示" width="250">
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />确定删除该数据吗？
      </p>
      <div slot="footer">
        <Button @click='delModal=false'>取消</Button>
        <Button type="primary" @click='confirmDel'>确定</Button>
      </div>
    </Modal>

    <Modal v-model="delImgModal" title="提示" width="250">
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />确定删除该图片吗？
      </p>
      <div slot="footer">
        <Button @click='delImgModal=false'>取消</Button>
        <Button type="primary" @click='confirmDelImg'>确定</Button>
      </div>
    </Modal>
  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import {
    mapState
  } from 'vuex'
  import {
    permission
  } from '@/config/permission.js'
  import {
    formatDate
  } from '@/config/publicTool.js' // 日期转换,//调用的时候formatDate(),不需要this
  // 上传组件
  import UploadTool from '../../components/uploadTool/uploadTool.vue'

  // 接口
  import {
    getList,
    add,
    put,
    del,
    delImg

  } from '@/api/banner-group/banner'
  import {
    tableOption
  } from '../../../data/banner-group/banner.js'
  import Tables from '_c/tables'
  import {
    uploadImgPathList
  } from '@/config/global.js'
  import {
    getTableData
  } from '@/api/data'

  export default {
    name: 'tables_page',
    components: {
      Tables,
      UploadTool
    },
    created() {
      let _this = this
      this.$nextTick(function() {
        // 权限校验
        _this.role_add = permission(this.roles, 'banner/add')
        _this.role_edit = permission(this.roles, 'banner/edit')
        _this.role_del = permission(this.roles, 'banner/delete')

      })
      this.getList()
    },
    watch: {

    },
    mounted() {

    },
    computed: {
      ...mapState({
        roles: state => state.user.roles,
        prodGroupBasicObj: state => state.share.prodGroupBasicObj,
      }),

    },
    data() {
      return {
        role_add: false,
        role_edit: false,
        role_del: false,
        delImgModal: false,
        delModal: false,
        createModal: false,
        createTitle: '添加',
        isAdd: true, // 新增true,修改false
        detailModal: false,
        loadingText: '',
        tableOption: tableOption,
        page: {
          current: 1,
          total: 0,
          pageSize: 10,

        },
        data: {
          detail: [],
          list: [],
          locationList: []

        },
        formValidate: {
          name: '',
          status: '1',
          location: '',
          sort: 0

        },
        isDisable: false, // 新增时提交按钮点击状态
        isLoading: false, // 新增时提交按钮loading状态

        ruleValidate: {
          name: [{
            required: true,
            message: '请输入标题名称',
            trigger: 'blur'
          }],
          location: [{
            required: true,
            message: '请选择位置',
            trigger: 'change'
          }]

        },
        rowId: 0,
        previewImgModal: false,
        uploadType: '', // 上传按钮判断
        uploadIndex: 0,
        fromChild: {
          selectedImgList: []
        },
        uploadModal: false,
        showUpload: false,
        uploadImgPathList: uploadImgPathList,
        // 上传
        tableOption: tableOption,
        isClosable: false,
        delImgId: 0,
        delImageIndex: '',
        editInitImageArr: [] //编辑功能从后台返回的图片初始数据
      }
    },
    methods: {
      // 列表数据
      getList() {
        let _this = this
        let params = {
          page: this.page.current,
        }

        getList(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.list = result.list
            _this.page.total = result.total
            _this.page.pageSize = result.size
            _this.data.locationList = result.location
          }
        }).catch(function(error) {
          // 异常

        })
      },
      changepage(e) {
        this.page.current = e;
        this.getList();

      },
      // 刷新
      refresh() {

        this.getList()
      },
      // 新增
      create() {
        if (!this.role_add) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.createModal = true

        this.createTitle = '添加轮播'
        this.isAdd = true
        this.formValidate = {} // 表单重置
        this.formValidate.status = '1';
        this.prodGroupBasicObj.album_imageArr = {}
        this.handleReset('formValidate') // 验证重置
      },
      // 修改
      edit(row) {
        if (!this.role_edit) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.createModal = true
        this.createTitle = '编辑轮播'
        this.isAdd = false
        this.formValidate = {} // 表单重置
        this.formValidate = JSON.parse(JSON.stringify(row))
        this.formValidate.location = this.formValidate.location.toString()
        this.formValidate.status = this.formValidate.status.toString()


        this.prodGroupBasicObj.album_imageArr = this.formValidate.image
        this.editInitImageArr = this.formValidate.image
        this.handleReset('formValidate') // 验证重置
      },
      handleReset(name) {
        this.$refs[name].resetFields()
      },
      save(name) {

        let _this = this

        if (_this.prodGroupBasicObj.album_imageArr.length <= 0 || _this.prodGroupBasicObj.album_imageArr.length ==
          undefined) {
          _this.$Message.error('请上传图片')
          return
        }

        if (_this.prodGroupBasicObj.album_imageArr.length > 5) {
          _this.$Message.error('上传的图片不能超过5张')
          return
        }

        this.$refs[name].validate((valid) => {
          if (valid) {
            if (_this.isAdd) {
              // 新增
              let obj = {
                name: _this.formValidate.name,
                location: _this.formValidate.location,
                status: _this.formValidate.status,
                extend: _this.prodGroupBasicObj.album_imageArr
              }

              // 新增接口
              add(obj).then(res => {
                if (res.data.status == 1) {

                  _this.createModal = false
                  _this.getList() // 重新刷新数据
                  _this.$Message.success('操作成功')
                } else {
                  _this.createModal = false
                  // axios响应拦截
                }
              }).catch(function(error) {
                // 异常
                _this.createModal = false
                console.log(error)
              })
            } else {
              // 修改

              let obj = {
                id: _this.formValidate.id,
                name: _this.formValidate.name,
                location: _this.formValidate.location,
                status: _this.formValidate.status,
                extend: _this.prodGroupBasicObj.album_imageArr

              }

              // 修改接口
              put(obj).then(res => {
                if (res.data.status == 1) {
                  _this.uploadType = ''
                  _this.uploadIndex = 0
                  _this.fromChild.selectedImgList = []
                  _this.createModal = false
                  _this.showUpload = false
                  _this.getList() // 重新刷新数据
                  _this.$Message.success('操作成功')
                } else {

                }
              }).catch(function(error) {
                // 异常
                console.log(error)
              })
            }

          } else {
            this.$Message.error('请输入必填项!')
          }
        })
      },
      upload(type, index) {
        // type为上传的类型，‘cover’封面
        this.uploadModal = true
        this.showUpload = true
        this.uploadType = type
        this.uploadIndex = index
      },
      getSelectedImgList(e) {
        this.fromChild.selectedImgList = e
      },
      cancelUploadModal() {
        this.uploadModal = false
        this.showUpload = false
      },
      confirm(type) {
        let _this = this

        let obj = this.prodGroupBasicObj;
        if (this.isAdd) {
          obj.album_imageArr = this.fromChild.selectedImgList.map((res => {
            return {
              url: res.url,
              extension: res.extension,
              file_name: res.path_name,
              sort: 0,
              status: true
            }
          }))
        } else {
          var temp = this.fromChild.selectedImgList.map((res => {
            return {
              url: res.url,
              extension: res.extension,
              file_name: res.path_name,
              sort: 0,
              status: true
            }
          }))

          //数据库返回的图片和新增加选中的图片合并
          obj.album_imageArr = this.editInitImageArr.concat(temp);

        }

        this.uploadModal = false

      },


      // 删除
      del(row) {
        if (!this.role_del) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.delId = row.id
        this.delModal = true
        // 删除接口
      },
      confirmDel() {
        let _this = this
        let obj = {
          id: this.delId
        }
        del(obj).then(res => {
          if (res.data.status == 1) {

            _this.delModal = false
            _this.$Message.success('操作成功')
            _this.getList() // 重新刷新数据
          } else {
            _this.delModal = false

          }
        }).catch(function(error) {
          // 异常
          _this.delModal = false
          console.log(error)
        })
      },
      delImg(item, index) {
        this.delImgModal = true;
        this.delImgId = item.id
        this.delImageIndex = index
      },
      confirmDelImg() {
        let _this = this
        let obj = {
          id: this.delImgId
        }
        delImg(obj).then(res => {
          if (res.data.status == 1) {

            _this.editInitImageArr.splice(this.delImageIndex, 1);
            let obj = _this.prodGroupBasicObj;
            var temp = _this.fromChild.selectedImgList.map((res => {
              return {
                url: res.url,
                extension: res.extension,
                file_name: res.path_name,
                sort: 0,
                status: true
              }
            }))
            obj.album_imageArr = _this.editInitImageArr.concat(temp);

            _this.delImgModal = false
            _this.$Message.success('操作成功')
            _this.getList() // 重新刷新数据
          } else {
            _this.delImgModal = false

          }
        }).catch(function(error) {
          // 异常
          _this.delImgModal = false
          console.log(error)
        })


      }
    }

  }
</script>

<style lang="scss">
  @import "./index";
</style>
